package uc.org.jkas.model;
import org.jkas.core.Model;
import java.util.HashMap;
public class MembersM extends Model
{ 
	public MembersM()
	{
	 primaryKey("uid");
	}

	public HashMap<String,String> getByName(String name)
	{   HashMap<Integer,Object> params=new HashMap<Integer,Object>();
	    params.put(1,name);
		return this.where("username=?").prepareRows(params);
	}

	public HashMap<String,String> getByMobile(String mobile)
	{   HashMap<Integer,Object> params=new HashMap<Integer,Object>();
	    params.put(1,mobile);
		return this.where("mobile=?").prepareRows(params);
	}

	public HashMap<String,String> getByEmail(String email)
	{   HashMap<Integer,Object> params=new HashMap<Integer,Object>();
	    params.put(1,email);
		return this.where("email=?").prepareRows(params);
	}

    public boolean exists(String username,String mobile,String email)
	{return exists(username,mobile,email,0);
	}
	public boolean exists(String username,String mobile,String email,int uid)
	{boolean res=false;
	   HashMap<String,String> info=null;
			      this.where(strc("username='",username,"'"));
				  if(!isEmpty(email))
				    {this.or(strc("email='",email,"'"));
				    }
					if(!isEmpty(mobile))
				    {this.or(strc("mobile='",mobile,"'"));
				    }
					info=this.getRows();
					if(info!=null && !info.isEmpty())
		             { if(uid>0 && uid==toInt(info.get("uid")))
						 {res=false;}
					     else
						 {
						   res=true;
						 }
		             }
	 return res;
	}

	/*
	0:don't exists
	1:username exists
	2:mobile exists
	3:email exists
	*/

	public int checkExists(String username,String mobile,String email)
	{return checkExists(username,mobile,email,0);
	}

	public int checkExists(String username,String mobile,String email,int uid)
	{int res=0;
	  HashMap<String,String> info=null;
	  HashMap<Integer,Object> params=new HashMap<Integer,Object>();
            params.put(1,username);
		int userid=toInt(this.fields("uid").where("username=?").prepareOne(params));
		 if(userid>0 && userid!=uid)
		  { res=1; 
		  }
		   if(res==0 && !isEmpty(mobile))
			  {params.put(1,mobile);
			   userid=toInt(this.fields("uid").where("mobile=?").prepareOne(params));
			   if(userid>0 && userid!=uid)
				  {res=2;
				  }
			  }
			  if(res==0 && !isEmpty(email))
			  {
			   params.put(1,email);
			   userid=toInt(this.fields("uid").where("email=?").prepareOne(params));
			   if(userid>0 && userid!=uid)
				  {res=3;
				  }
			  }
	 return res;
	}

	public boolean validUserName(String username)
    {
	 String regex="^[a-zA-Z0-9\u4E00-\u9FA5_]+$";
	 return valid().check(regex,username);
	}

	public String encodePassword(String password,String salt)
	{String res="";
	  res=md5(strc(md5(password),salt));
	 return res;
	}
}